package com.ybkj.daijia.server.service.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.config.ErrandApi;
import com.ybkj.daijia.config.FreightApi;
import com.ybkj.daijia.config.PassengerApi;
import com.ybkj.daijia.config.SalesApi;
import com.ybkj.daijia.config.ZhuanApi;
import com.ybkj.daijia.config.ZhuanxianApi;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.event.model.ActivityCheckEvent;
import com.ybkj.daijia.server.event.model.ActivityReturnEvent;
import com.ybkj.daijia.server.mapper.CompanyMapper;
import com.ybkj.daijia.server.mapper.FirstOrderPassengerMapper;
import com.ybkj.daijia.server.mapper.OrderMapper;
import com.ybkj.daijia.server.mc.Enterprise;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Activity;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.sales.Activity.ActivityTarget;
import com.ybkj.daijia.server.sales.Activity.ActivityType;
import com.ybkj.daijia.server.sales.Activity.OrderType;
import com.ybkj.daijia.server.sales.ActivityRecord;
import com.ybkj.daijia.server.sales.ActivityVo;
import com.ybkj.daijia.server.service.ActivityService;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

/**
 * @author Shine
 */
@Service
public class DefaultActivityService implements ActivityService {

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private SalesApi salesApi;

    @Autowired
    private PassengerApi passengerApi;

    @Autowired
    private ZhuanApi zhuanApi;

    @Autowired
    private FreightApi freightApi;

    @Autowired
    private ZhuanxianApi zhuanxianApi;

    @Autowired
    private ErrandApi errandApi;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Autowired
    private FirstOrderPassengerMapper firstOrderPassengerMapper;


    /* (non-Javadoc)
     * @see com.ybkj.shop.service.AdminService#queryAll()
     */
    public Page<Activity> queryActivities(String activityEvent, String activityType) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        StringBuilder sb = new StringBuilder();
        sb.append(salesApi.getCouponRuleBaseURL() + SalesApi.QUERY_ACTIVITIES
            + "?appKey={appKey}&appId={appId}&sign={sign}&page={page}&rows={rows}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", (Pager.getPage() + 1) + "");
        kv.put("rows", Pager.getLimit() + "");

        if (!principal.isCompanyType()) {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            sb.append("&companyId={companyId}");
        }

        kv.put("activityEvent", activityEvent);
        sb.append("&activityEvent={activityEvent}");
        if (activityType != null) {
            kv.put("activityType", activityType);
            sb.append("&activityType={activityType}");
        }

        String result = salesApi.get(sb.toString(), kv, settingUtils.get());

        List<Activity> content = new ArrayList<Activity>();
        long total = 0;

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new Gson();
                content = gson.fromJson(ja.toString(), new TypeToken<List<Activity>>() {
                }.getType());
            }
        }

        if (principal.isCompanyType()) {
            if (total > 0) {
                for (Activity activity : content) {
                    activity.setCompany(companyMapper.selectByPrimaryKey(activity.getCompanyId()));
                }
            }
        }

        return new PageImpl<Activity>(content, pageable, total);

    }


    @Transactional(rollbackFor = Exception.class)
    public Result<Activity> stop(Long activityId) {

        Result<Activity> result = new Result<Activity>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();

        String api = SalesApi.STOP_ACTIVITY;
        api = api.replaceAll("\\{activityId\\}", String.valueOf(activityId));
        sb.append(
            salesApi.getCouponRuleBaseURL() + api + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        String resultStr = salesApi.put(sb.toString(), kv, settingUtils.get());

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
        } else {
            result.setSuccess(true);
        }

        return result;

    }

    @Override
    public Activity findOne(Long id) {
        Result<Activity> result = salesApi.findOneActivity(id);

        return result.getResult();

    }

    @Override
    public ActivityRecord findOneRecord(Long id) {
        Result<ActivityRecord> result = salesApi.findOneActivityRecord(id);

        return result.getResult();
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Activity> delete(Long activityId) {

        Result<Activity> result = new Result<Activity>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();

        String api = SalesApi.DELETE_ACTIVITY;
        api = api.replaceAll("\\{activityId\\}", String.valueOf(activityId));
        sb.append(
            salesApi.getCouponRuleBaseURL() + api + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        String resultStr = salesApi.put(sb.toString(), kv, settingUtils.get());

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
        } else {
            result.setSuccess(true);
        }

        return result;

    }


    @Override
    public Page<Map<String, Object>> queryByCompany(Long companyId, Integer page, Integer limit) {

        return null;
//		Pageable pageable = new PageRequest(page, limit);
//		
//		long totalElements=activityMapper.countLastedByCompany(companyId);
//		List<Activity> alist = new ArrayList<Activity>();
//		if(totalElements>0){
//			alist=activityMapper.selectLastedByCompany(companyId,page*limit,limit);
//		}
//		
//		List<Map<String, Object>> mapList=new ArrayList<Map<String,Object>>();
//		if(CollectionUtils.isNotEmpty(alist)){
//			
//			List<Activity> activitylist = new ArrayList<Activity>();
//			activitylist.addAll(alist);
//			
//			Collections.sort(activitylist, new Comparator<Activity>() {
//	            public int compare(Activity arg0, Activity arg1) {
//	                return arg0.getSort().compareTo(arg1.getSort());
//	            }
//	        });
//			
//			Setting setting = settingUtils.get();
//			for (Activity activity : activitylist) {
//				Map<String, Object> map =new HashMap<String, Object>();
//				map.put("activityId", activity.getId());
//				map.put("activityTitle", activity.getTitle());
//				map.put("activityContent", HtmlHelper.html2Text(activity.getContent()));
//				map.put("activityPicture", setting.getWebUrl()+"/"+activity.getPicture());
//				map.put("startTime", activity.getStart().getTime());
//				map.put("endTime", activity.getEnd().getTime());
//				if(activity.isStoped()){
//					map.put("activityStatus", 3);
//				}
//				else{
//					map.put("activityStatus", activity.getTimeStatus());
//				}
//				
//				mapList.add(map);
//			}
//			
//		}
//		
//		Page<Map<String, Object>> result = new PageImpl<Map<String, Object>>(mapList, pageable, totalElements);
//		return result;
    }

    @Override
    public Result<Activity> create(Activity activity) {

        Result<Activity> result = new Result<Activity>();
        result.setSuccess(false);

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("activityRange", activity.getActivityRange());

        kv.add("activityEvent", activity.getActivityEvent().toString());

        if (null != activity.getActivityTarget()) {
            kv.add("activityTarget", activity.getActivityTarget().toString());
        }
        if (null != activity.getActivityType()) {
            kv.add("activityType", activity.getActivityType().toString());
        }

        if (StringUtils.isNotBlank(activity.getGradeIds())) {
            kv.add("gradeIds", "," + activity.getGradeIds() + ",");
        }

        kv.add("gradeNames", activity.getGradeNames());

        kv.add("passengerFromSource", activity.getPassengerFromSource());

        if (StringUtils.isNotBlank(activity.getSharePlatforms())) {
            kv.add("sharePlatforms", "," + activity.getSharePlatforms() + ",");
        }

        kv.add("sharePlatformNames", activity.getSharePlatformNames());

        if (null != activity.getShareTimes()) {
            kv.add("shareTimes", activity.getShareTimes().toString());
        }

        if (null != activity.getRestriction()) {
            kv.add("restriction", activity.getRestriction().toString());
        }

        kv.add("orderFromSource", activity.getOrderFromSource());

        if (null != activity.getCompleteTimes()) {
            kv.add("completeTimes", activity.getCompleteTimes().toString());
        }

        if (null != activity.getOrderType()) {
            kv.add("orderType", activity.getOrderType().toString());
        }

        kv.add("companyIds", "," + activity.getCompanyIds() + ",");

        kv.add("companyNames", activity.getCompanyNames());

        kv.add("start", activity.getStart().toString());

        if (null != activity.getEnd()) {
            kv.add("end", activity.getEnd().toString());
        }
        if (null != activity.getActivityType()) {
            if (activity.getActivityType().equals(ActivityType.cash)) {
                kv.add("money", activity.getMoney().toString());
            } else if (activity.getActivityType().equals(ActivityType.coupon)) {
                kv.add("couponIds", activity.getCouponIds());
                kv.add("couponAmounts", activity.getCouponAmounts());
            }
        }
        if (null != activity.getRechargingMoney()) {
            kv.add("rechargingMoney", activity.getRechargingMoney().toString());
        }

        if (null != activity.getBackgroudColor()) {
            kv.add("backgroudColor", activity.getBackgroudColor());
        }
        if (null != activity.getActivityContent()) {
            kv.add("activityContent", activity.getActivityContent());
        }
        if (null != activity.getActivityImage()) {
            kv.add("activityImage", activity.getActivityImage());
        }
        if (StringUtils.isNotBlank(activity.getMessageType())) {
            kv.add("messageType", activity.getMessageType().toString());
        }

        if (null != activity.getFreeType()) {
            kv.add("freeType", activity.getFreeType().toString());
        }
        if (null != activity.getOtherMoney()) {
            kv.add("otherMoney", activity.getOtherMoney().toString());
        }

        kv.add("companyId", principal.getCompanyId().toString());
        if (null != activity.getLineId()) {
            kv.add("lineId", activity.getLineId().toString());
        }
        if (null != activity.getLineName()) {
            kv.add("lineName", activity.getLineName());
        }
        if (null != activity.getReviewGrade()) {
            kv.add("reviewGrade", activity.getReviewGrade().toString());
        }

        String resultStr = salesApi
            .post(salesApi.getCouponRuleBaseURL() + SalesApi.CREATE_ACTIVITY, kv,
                settingUtils.get());
        JSONObject jo = new JSONObject(resultStr);
        Integer code = jo.getInt("code");
        if (code == 0) {
            result.setSuccess(true);
        } else {
            result.setMessage(jo.getString("message"));
        }

        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Activity> update(Activity activity) {

        Result<Activity> result = new Result<Activity>();
        result.setSuccess(false);

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("id", activity.getId().toString());

        if (null != activity.getActivityTarget()) {
            kv.add("activityTarget", activity.getActivityTarget().toString());
        }

        if (StringUtils.isNotBlank(activity.getGradeIds())) {
            kv.add("gradeIds", "," + activity.getGradeIds() + ",");
        }

        kv.add("gradeNames", activity.getGradeNames());

        kv.add("passengerFromSource", activity.getPassengerFromSource());

        if (StringUtils.isNotBlank(activity.getSharePlatforms())) {
            kv.add("sharePlatforms", "," + activity.getSharePlatforms() + ",");
        }

        kv.add("sharePlatformNames", activity.getSharePlatformNames());

        kv.add("orderFromSource", activity.getOrderFromSource());

        kv.add("companyIds", "," + activity.getCompanyIds() + ",");

        kv.add("companyNames", activity.getCompanyNames());

        if (null != activity.getEnd()) {
            kv.add("end", activity.getEnd().toString());
        }
        if (null != activity.getBackgroudColor()) {
            kv.add("backgroudColor", activity.getBackgroudColor());
        }
        if (null != activity.getActivityContent()) {
            kv.add("activityContent", activity.getActivityContent());
        }
        if (null != activity.getActivityImage()) {
            kv.add("activityImage", activity.getActivityImage());
        }
        if (StringUtils.isNotBlank(activity.getMessageType())) {
            kv.add("messageType", activity.getMessageType().toString());
        }

        String resultStr = salesApi
            .post(salesApi.getCouponRuleBaseURL() + SalesApi.UPDATE_ACTIVITY, kv,
                settingUtils.get());
        JSONObject jo = new JSONObject(resultStr);
        Integer code = jo.getInt("code");
        if (code == 0) {
            result.setSuccess(true);
        } else {
            result.setMessage(jo.getString("message"));
        }

        return result;
    }


    @Override
    public Result<ActivityVo> phoneGift(Long activityId, String phone) {

        Result<ActivityVo> result = new Result<ActivityVo>();

        Result<Passenger> resultPassenger = passengerApi
            .findOnePassengerByPhone(phone, settingUtils.get());
        Passenger passenger = resultPassenger.getResult();

        if (passenger == null) {
            Company mainCompany = companyMapper.selectMainCompany();
            passenger = new Passenger();
            passenger.setPhone(phone);
            passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_ACTIVITY);
            passenger.setType(Passenger.TYPE_PASSENGER);
            passenger.setAllowOverdraw(false);
            passenger.setCompanyId(mainCompany.getId());
            passenger.setCompanyName(mainCompany.getAbbreviation());

            Result<Passenger> result_passenger = passengerApi
                .createPersonal(passenger, settingUtils.get());
            if (result_passenger.isSuccess()) {
                passenger = result_passenger.getResult();

                //新注册活动
                ReactorVo rVo = new ReactorVo();
                rVo.setPassenger(passenger);
                rVo.setActivityEvent(ActivityEvent.newRegister);
                ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                applicationEventMulticaster.multicastEvent(activityCheckEvent);
            } else {
                result.setSuccess(false);
                result.setMessage(result_passenger.getMessage());
                return result;
            }
        }

        Enterprise enterprise = null;

        if (null != passenger && passenger.getType().equals(1)) {
            enterprise = passengerApi
                .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get()).getResult();
        }

        if ((null != passenger && passenger.getType().equals(0)) || (null != passenger && passenger
            .getType().equals(1) && null != enterprise)) {
            Activity activity = salesApi.findOneActivity(activityId).getResult();
            if (null != activity) {

                if (activity.getCompanyIds()
                    .contains("," + String.valueOf(passenger.getCompanyId()) + ",")) {
                    if ((activity.getActivityTarget().equals(ActivityTarget.all)) ||
                        (activity.getActivityTarget().equals(ActivityTarget.passenger) && passenger
                            .getType().equals(0)) ||
                        (activity.getActivityTarget().equals(ActivityTarget.enterprise) && passenger
                            .getType().equals(1))) {

                        boolean gradeOk = false;
                        if (passenger.getType().equals(0)) {
                            if (null == passenger.getGrade_id() || StringUtils
                                .isBlank(activity.getGradeIds()) || activity.getGradeIds()
                                .contains("," + String.valueOf(passenger.getGrade_id()) + ",")) {
                                gradeOk = true;
                            }
                        } else if (passenger.getType().equals(1)) {
                            if (null == enterprise.getGrade_id() || StringUtils
                                .isBlank(activity.getGradeIds()) || activity.getGradeIds()
                                .contains("," + String.valueOf(enterprise.getGrade_id()) + ",")) {
                                gradeOk = true;
                            }
                        }

                        if (gradeOk) {
                            if (null != activity.getOrderType() && null != activity
                                .getCompleteTimes()) {
                                Integer completeTimes = activity.getCompleteTimes();//满足的完成次数
                                Integer restriction = activity.getRestriction();//限制领取次数

                                Long completeTimesNow = 0L;//已经完成的次数

                                Date startDate = new Date(activity.getStart());
                                Date endDate = null;
                                if (null != activity.getEnd()) {
                                    endDate = new Date(activity.getEnd());
                                }

                                if (activity.getOrderType().equals(OrderType.daijia)) {
                                    completeTimesNow = orderMapper
                                        .countFinishedByPassengerWithDate(passenger.getId(), null,
                                            startDate, endDate);
                                } else if (activity.getOrderType().equals(OrderType.zhuanche)) {
                                    completeTimesNow = zhuanApi
                                        .countFinishedByPassengerAndFinishTime(passenger.getId(),
                                            null, startDate, endDate, settingUtils.get());
                                } else if (activity.getOrderType().equals(OrderType.freight)) {
                                    completeTimesNow = freightApi
                                        .countFinishedByPassengerAndFinishTime(passenger.getId(),
                                            null, startDate, endDate, settingUtils.get());
                                } else if (activity.getOrderType().equals(OrderType.zhuanxian)) {
                                    completeTimesNow = zhuanxianApi
                                        .countFinishedByPassengerAndFinishTime(passenger.getId(),
                                            null, startDate, endDate, settingUtils.get());
                                } else if (activity.getOrderType().equals(OrderType.errand)) {
                                    completeTimesNow = errandApi
                                        .countFinishedByPassengerAndFinishTime(passenger.getId(),
                                            null, startDate, endDate, settingUtils.get());
                                }

                                if (completeTimesNow != 0
                                    && completeTimesNow % completeTimes == 0) {

                                    if (restriction == 0
                                        || (completeTimesNow / completeTimes) <= restriction) {
                                        Result<ActivityVo> result_activityvo = salesApi
                                            .startActivity(activity, passenger, enterprise);
                                        if (result_activityvo.isSuccess()) {

                                            ActivityVo activityVo = result_activityvo.getResult();
                                            ActivityRecord activityRecord = activityVo
                                                .getActivityRecord();
                                            if (null != activityRecord.getId()) {
                                                result.setSuccess(true);
                                                result.setResult(activityVo);
                                                if (StringUtils
                                                    .isNotBlank(activity.getMessageType())) {
                                                    ActivityReturnEvent activityReturnEvent = new ActivityReturnEvent(
                                                        activity, activityVo,
                                                        activityRecord.getMemo(), passenger);
                                                    applicationEventMulticaster
                                                        .multicastEvent(activityReturnEvent);
                                                }
                                            } else {
                                                result.setSuccess(false);
                                                result.setMessage("已超出可领取优惠券数量！");
                                            }

                                        } else {
                                            result.setSuccess(false);
                                            result.setMessage(result_activityvo.getMessage());
                                        }
                                    } else {
                                        result.setSuccess(false);
                                        result.setMessage("您已参与了该活动，不能再次参与！");
                                    }

                                } else {
                                    result.setSuccess(false);
                                    result.setMessage("订单完成次数不符合活动条件");
                                }
                            } else {

                                Integer restriction = activity.getRestriction();//限制领取次数
                                Long activityRecordTimes = salesApi
                                    .countActivityRecord(passenger.getId(),
                                        activity.getId());//已经参与次数

                                if (restriction == 0 || activityRecordTimes < restriction) {
                                    Result<ActivityVo> result_activityvo = salesApi
                                        .startActivity(activity, passenger, enterprise);
                                    if (result_activityvo.isSuccess()) {

                                        ActivityVo activityVo = result_activityvo.getResult();
                                        ActivityRecord activityRecord = activityVo
                                            .getActivityRecord();
                                        if (null != activityRecord.getId()) {
                                            result.setSuccess(true);
                                            result.setResult(activityVo);

                                            if (StringUtils.isNotBlank(activity.getMessageType())) {
                                                ActivityReturnEvent activityReturnEvent = new ActivityReturnEvent(
                                                    activity, activityVo, activityRecord.getMemo(),
                                                    passenger);
                                                applicationEventMulticaster
                                                    .multicastEvent(activityReturnEvent);
                                            }
                                        } else {
                                            result.setSuccess(false);
                                            result.setMessage("已超出可领取优惠券数量！");
                                        }

                                    } else {
                                        result.setSuccess(false);
                                        result.setMessage(result_activityvo.getMessage());
                                    }
                                } else {
                                    result.setSuccess(false);
                                    result.setMessage("您已参与了该活动，不能再次参与！");
                                }

                            }
                        } else {
                            result.setSuccess(false);
                            result.setMessage("手机号用户等级不符合活动条件");
                        }

                    } else {
                        result.setSuccess(false);
                        result.setMessage("手机号用户类型不符合活动条件");
                    }
                } else {
                    result.setSuccess(false);
                    result.setMessage("手机号用户所属公司不符合活动条件");
                }
            }
        }

        return result;

    }


    @Override
    public Page<ActivityRecord> queryActivityRecord(Long activityId, String phone, Long companyId,
        String startTime, String endTime, Integer page, Integer rows) throws ParseException {
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        Result<ActivityRecord> result = new Result<ActivityRecord>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();

        String api = SalesApi.QUERY_ACTIVITY_RECORD;
        sb.append(salesApi.getCouponRuleBaseURL() + api
            + "?appKey={appKey}&appId={appId}&sign={sign}&activityId={activityId}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("activityId", activityId.toString());
        if (page != null) {
            kv.put("page", (page + 1) + "");
            sb.append("&page={page}");
        }
        if (rows != null) {
            kv.put("rows", rows.toString());
            sb.append("&rows={rows}");

        }
        if (StringUtils.isNotBlank(phone)) {
            kv.put("phone", phone);
            sb.append("&phone={phone}");
        }
        if (companyId != null) {
            kv.put("companyId", String.valueOf(companyId));
            sb.append("&companyId={companyId}");
        }
        if (StringUtils.isNotBlank(startTime)) {
            SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
            Date start = sm.parse(startTime);
            kv.put("startTime", String.valueOf(start.getTime()));
            sb.append("&startTime={startTime}");
        }
        if (StringUtils.isNotBlank(endTime)) {
            try {
                Date end = DateUtils.parseDate(endTime, "yyyy-MM-dd");
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(end);
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                end = calendar.getTime();

                kv.put("endTime", String.valueOf(end.getTime()));
                sb.append("&endTime={endTime}");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        String resultStr = passengerApi.get(sb.toString(), kv, settingUtils.get());

        List<ActivityRecord> content = new ArrayList<ActivityRecord>();
        long total = 0;

        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new Gson();
                content = gson.fromJson(ja.toString(), new TypeToken<List<ActivityRecord>>() {
                }.getType());
            }
        }

        return new PageImpl<ActivityRecord>(content, pageable, total);
    }


    @Override
    public Boolean findFreeFirstOrder(Long passengerId, String orderType, String orderFromSource) {
        Boolean success = false;
        Result<Passenger> onePassenger = passengerApi
            .findOnePassenger(passengerId, settingUtils.get());
        Passenger passenger = onePassenger.getResult();
        Enterprise enterprise = null;
        if (null != passenger && passenger.getType().equals(1)) {
            enterprise = passengerApi
                .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get()).getResult();
        }

        Result<Activity> activites = salesApi.findOneByCompanyId(passenger.getCompanyId());

        List<Activity> list = activites.getData();
        if (!CollectionUtils.isEmpty(list)) {
            for (Activity activity : list) {
                if (activity.getCompanyIds()
                    .contains("," + String.valueOf(passenger.getCompanyId()) + ",")) {
                    if ((activity.getActivityTarget().equals(ActivityTarget.all)) ||
                        (activity.getActivityTarget().equals(ActivityTarget.passenger) && passenger
                            .getType().equals(0)) ||
                        (activity.getActivityTarget().equals(ActivityTarget.enterprise) && passenger
                            .getType().equals(1))) {

                        boolean gradeOk = false;
                        if (passenger.getType().equals(0)) {
                            if (null == passenger.getGrade_id() || StringUtils
                                .isBlank(activity.getGradeIds()) || activity.getGradeIds()
                                .contains("," + String.valueOf(passenger.getGrade_id()) + ",")) {
                                gradeOk = true;
                            }
                        } else if (passenger.getType().equals(1)) {
                            if (null == enterprise.getGrade_id() || StringUtils
                                .isBlank(activity.getGradeIds()) || activity.getGradeIds()
                                .contains("," + String.valueOf(enterprise.getGrade_id()) + ",")) {
                                gradeOk = true;
                            }
                        }

                        if (gradeOk) {
                            if (activity.getOrderFromSource().contains(orderFromSource)) {
                                if (activity.getOrderType().equals(orderType)) {
                                    if (firstOrderPassengerMapper
                                        .selectAll(passenger.getId(), orderType) > 0) {
                                        success = true;
                                    }
                                }
                            }
                        }
                    }
                }

            }
        }

        return success;
    }


    @Override
    public Long countActivityRecord(Long activityId, String phone,
        Long companyId, String startTime, String endTime)
        throws ParseException {
        long count = 0;

        Result<ActivityRecord> result = new Result<ActivityRecord>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();

        String api = SalesApi.COUNT_BY_PARAM;
        sb.append(salesApi.getCouponRuleBaseURL() + api
            + "?appKey={appKey}&appId={appId}&sign={sign}&activityId={activityId}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("activityId", activityId.toString());
        if (StringUtils.isNotBlank(phone)) {
            kv.put("phone", phone);
            sb.append("&phone={phone}");
        }
        if (companyId != null) {
            kv.put("companyId", String.valueOf(companyId));
            sb.append("&companyId={companyId}");
        }
        if (StringUtils.isNotBlank(startTime)) {
            SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
            Date start = sm.parse(startTime);
            kv.put("startTime", String.valueOf(start.getTime()));
            sb.append("&startTime={startTime}");
        }
        if (StringUtils.isNotBlank(endTime)) {
            SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
            Date end = sm.parse(endTime);
            kv.put("endTime", String.valueOf(end.getTime()));
            sb.append("&endTime={endTime}");

        }

        String resultStr = salesApi.get(sb.toString(), kv, settingUtils.get());

        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                count = jo.getLong("data");
            }
        }

        return count;
    }


}
